﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows.Input;
using CPETwit.WPFClient.Business.Service;
using CPETwit.WPFClient.Business.TwitterServiceReference;
using CPETwit.WPFClient.Command;
using CPETwit.WPFClient.Common;

namespace CPETwit.WPFClient.ViewModel
{
    public class ResearchUsersViewModel : INotifyPropertyChanged
    {
        #region INotifyPropertyChanged

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

        #region Fields

        private ObservableCollection<User> _users;
        private string _research;
        private ICommand _followCommand;

        #endregion

        #region Properties

        public string Research
        {
            get { return _research; }
            set
            {
                _research = value;
                OnPropertyChanged("Research");
                if (_research != "Recherche de contacts")
                    LoadUserFromResearch(_research);
            }
        }
        public ObservableCollection<User> Users
        {
            get
            {
                return _users;
            }
            private set
            {
                _users = value;
                OnPropertyChanged("Users");
            }
        }
        public ICommand FollowCommand
        {
            get
            {
                return _followCommand ??
                    new RelayCommand(param => FollowUser(param as User),
                                     param => CanFollowUser());
            }
        }

        private bool CanFollowUser()
        {
            return CommonData.LOGGED_USER != null;
        }

        private void FollowUser(User user)
        {
            ServiceManager.ManageFollow(user);
            ServiceManager.RefreshCurrentUser();
            LoadUserFromResearch(_research);
        }

        #endregion

        /// <summary>
        /// Constructeur par défaut.
        /// </summary>
        public ResearchUsersViewModel()
        {
            _users = new ObservableCollection<User>();
        }


        /// <summary>
        /// Chargement des tweets d'un utilisateur.
        /// </summary>
        public void UpdateViewModel()
        {
            Users.Clear();
        }

        private void LoadUserFromResearch(string research)
        {
            Users.Clear();
            IEnumerable<User> users = ServiceManager.GetUsersFromResearch(research);
            if(users != null)
                Users = new ObservableCollection<User>(users);
        }
    }
}
